import React, { useEffect, useMemo, useState } from "react";
import PropTypes from "prop-types";
import BetterScroll from "pages/components/betterScroll";
import { NavBar, List, Skeleton, Empty, Button, Dialog, Popup, Toast } from "antd-mobile";
import axios from "src/api/index";
import Upload from "./upload";
import Btns from "./btns";
import {
    FILE_URL,
    MD_TYPE_ID,
    CURRENT_PER_URL,
    API_URL,
    PDF_URL,
    FILE_VIEW,
    FILE_VIEW_ONLINE,
} from "src/config";
import { PreviewPdf, isNormalBrowser } from "src/utils/index";
import Cookies from "js-cookie";

const page = 1,
    limit = 15;

const FileList = props => {
    const [tableData, setTableData] = useState([]);
    const [infoVisible, setInfoVisible] = useState(false);
    const [current, setCurrent] = useState(null);
    const [isAdd, setIsAdd] = useState(false);

    const { detailPage, typeId, infoKid, moduleId, user } = props;

    useEffect(() => {
        if (detailPage === "add") {
            typeId && initDatas();
        } else {
            getTableDatas({
                joinId: infoKid,
            });
        }
    }, [typeId]);

    const initDatas = async () => {
        const res = await axios({
            url: "/pqsprojTableData_init",
            data: {
                page,
                limit,
                eventId: typeId,
                joinId: infoKid,
                moduleId,
            },
        });
        if (res.success) {
            afterGetData(res.data);
        }
    };

    const getTableDatas = async params => {
        const res = await axios({
            method: "GET",
            url: "pqsprojTableData_query_page",
            data: params,
        });
        if (res.success) {
            afterGetData(res.data);
        }
    };

    const afterGetData = fileData => {
        const tableData = fileData.map(file => {
            const { dataSrcName, allCount } = file;
            return {
                ...file,
                dataSrcName: `${dataSrcName}（${allCount ? allCount : 0}）`,
            };
        });
        setTableData(tableData);
    };

    const visibleCb = () => {
        setInfoVisible(false);
        if (!isAdd) return;
        getTableDatas({
            joinId: infoKid,
        });
    };

    const hasData = tableData?.length;
    const canUpload = ["add", "edit"].includes(detailPage);

    return (
        <div className="file-list-container">
            <div className="sub">清单项列表</div>
            <div className="scroll-container">
                <div ref={scroll}>
                    <div className={`${hasData ? "file-info-container" : "empty"}`}>
                        {hasData ? (
                            tableData?.map((table, idx) => {
                                const { kid, dataName, dataSrcName } = table;
                                return (
                                    <div className="list-container" key={kid}>
                                        <List.Item
                                            arrowIcon={false}
                                            clickable={false}
                                            onClick={e => {
                                                setCurrent(table);
                                                setIsAdd(false);
                                                setInfoVisible(true);
                                            }}
                                        >
                                            <div className="content">
                                                <p>
                                                    <span>序号：</span>
                                                    <span>{idx + 1}</span>
                                                </p>
                                                <p>
                                                    <span>清单项名称：</span>
                                                    <span>{dataName}</span>
                                                </p>
                                                <p>
                                                    <span>数据来源：</span>
                                                    <span className="clickable">{dataSrcName}</span>
                                                </p>
                                            </div>
                                            <div className="btns">
                                                <Button
                                                    size="small"
                                                    color="primary"
                                                    fill="solid"
                                                    onClick={e => {
                                                        e.stopPropagation();
                                                        setCurrent(table);
                                                        setIsAdd(
                                                            canUpload
                                                        );
                                                        setInfoVisible(true);
                                                    }}
                                                    disabled={!canUpload}
                                                >
                                                    上传
                                                </Button>
                                            </div>
                                        </List.Item>
                                    </div>
                                );
                            })
                        ) : (
                            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                        )}
                    </div>
                </div>
            </div>
            <FileInfo
                visible={infoVisible}
                visibleCb={visibleCb}
                recordId={current?.kid}
                isAdd={isAdd}
                user={user}
                tableId={0}
                page={detailPage}
            />
        </div>
    );
};

export function FileInfo(props) {
    const [fileList, setFileList] = useState([]);
    const { visible, visibleCb, recordId, isAllFormat = "all", isAdd, user, tableId } = props;

    useEffect(() => {
        visible && recordId && getFileList();
    }, [visible]);

    const getFileList = async () => {
        const res = await axios({
            method: "get",
            url: "/getFileList",
            data: {
                recordId,
                tableId: 0,
            },
        });
        if (res.success) {
            let resData = res.data;
            if (isAllFormat === "all") {
                //全格式
            } else if (isAllFormat === "images") {
                //除图片格式
                resData = resData.filter(item => {
                    return (
                        item.ext === ".jpg" ||
                        item.ext === ".jpeg" ||
                        item.ext === ".png" ||
                        item.ext === ".gif"
                    );
                });
            } else {
                //文件格式
                resData = resData.filter(item => {
                    return (
                        item.ext !== ".jpg" &&
                        item.ext !== ".jpeg" &&
                        item.ext !== ".png" &&
                        item.ext !== ".gif" &&
                        item.ext !== ".bmp" &&
                        item.ext !== ".webp"
                    );
                });
            }

            const fileList = resData.map(item => {
                item.addDate = item.addDate.slice(0, 10);
                item.extName = item.ext.slice(1, item.ext.length);
                return item;
            });
            setFileList(fileList);
        }
    };

    const hasData = fileList?.length;

    const uploadFiles = async files => {
        const { userId, name, projId, orgId } = user;
        Promise.all(
            files.map(async file => {
                const res = axios({
                    url: "/wpfile/upload",
                    method: "POST",
                    data: {
                        userId,
                        userName: name,
                        projId: projId || orgId,
                        tableId,
                        recordId,
                        mdTypeId: MD_TYPE_ID || 105,
                        file,
                    },
                    headers: {
                        "Content-Type": "multipart/form-data",
                    },
                });
                return res;
            }),
        )
            .then(res => {
                getFileList();
            })
            .catch(err => {});
    };

    const delFile = async kid => {
        const isBack = await Dialog.confirm({ content: "此操作将永久删除数据, 是否继续?" });
        if (!isBack) return;
        const res = await axios({
            url: FILE_URL + "/wpfile/delbykid",
            method: "delete",
            params: { kid },
        });
        res.success && getFileList();
    };

    const viewFile = async record => {
        const isView = await Dialog.confirm({ content: "是否查看文件?" });
        if (!isView) return;

        if (record.svrFullPath) {
            Toast.show({
                icon: "loading",
                content: "",
                duration: FILE_VIEW_ONLINE ? 2000 : 0,
            });

            const url = (PDF_URL + record.svrFullPath).replace(/\\/g, "/");
            // if (!isNormalBrowser()) {
            //     const url = `${API_URL}/wpfile/download?dbName=GPMSPQS&kid=${record.kid}&ext=${record.ext}`;
            //     PreviewPdf(url);
            //     return;
            // }

            if (FILE_VIEW_ONLINE) {
                // 在线预览方式
                // let viewUrl = `${url}&fullfilename=${record.kid}${record.ext}&isApp=1`;
                PreviewPdf(record.svrFullPath);
            } else {
                //  downLoad 下载方式
                axios({
                    method: "GET",
                    customError: true,
                    _ingore: true,
                    url: FILE_VIEW,
                    params: {
                        fileName: `${record.kid}${record.ext}`,
                        cookies: `CRBIMSSOJWT=${Cookies.get("CRBIMSSOJWT")}`,
                        url,
                        isApp: 1,
                    },
                }).then(res => {
                    if (res.msg === "SUCCESS") {
                        Toast.show({
                            icon: "success",
                            content: "",
                        });
                        res.data && window.open(res.data);
                    } else {
                        Toast.show({
                            icon: "fail",
                            content: res.msg,
                        });
                    }
                });
            }
        } else {
            Toast.show({
                icon: "fail",
                content: "附件不存在!",
                afterClose: () => {},
            });
            return;
        }
    };

    const downFile = file => {
        if (CURRENT_PER_URL && file && file.tkyFileId) {
            // 附件预览地址
            //文件信息中的字段tkyFileId，title=文件信息中的字段title
            const path =
                CURRENT_PER_URL + `?fileId=${file.tkyFileId}&filename=${file.title || "文件下载"}`;
            window.open(path);
        }
    };

    const btns = [
        {
            label: "查看",
            key: "1",
            fn: file => viewFile(file),
            hidden: file => {},
        },
        {
            label: "删除",
            key: "2",
            fn: file => delFile(file.kid),
            hidden: file => !isAdd,
        },
        // {
        //     label: "下载",
        //     key: "3",
        //     fn: file => downFile(file),
        //     hidden: file => {},
        // },
    ];

    return (
        <Popup
            visible={visible}
            onMaskClick={visibleCb}
            onClose={visibleCb}
            bodyStyle={{ height: "78vh" }}
            showCloseButton
            className="file-info-container"
            closeOnMaskClick
            getContainer={false}
        >
            <div className="file-info-list">
                <h3>附件列表</h3>
                {isAdd && (
                    <Upload
                        tips="说明：图片格式限（jpg，jpeg，png），文件格式限（doc，docx，xls，xlxs，pdf)"
                        onRecive={uploadFiles}
                        isAllFormat="all"
                    />
                )}
                <div
                    className="scroll-container"
                    style={{ height: `calc(100% - ${isAdd ? 104 : 24}px)` }}
                >
                    <BetterScroll ref={scroll}>
                        <div className={`${hasData ? "file-info-container" : "empty"}`}>
                            {hasData ? (
                                fileList?.map((file, idx) => {
                                    const { kid, title, length, extName, addDate, userName } = file;
                                    return (
                                        <div className="list-container" key={kid}>
                                            <List.Item
                                                arrowIcon={false}
                                                clickable={false}
                                                onClick={e => {}}
                                            >
                                                <div className="content">
                                                    <p>
                                                        <span>文件名：</span>
                                                        <span>{title}</span>
                                                    </p>
                                                    <p>
                                                        <span>大小(字节):</span>
                                                        <span>{length}</span>
                                                    </p>
                                                    <p>
                                                        <span>格式：</span>
                                                        <span>{extName}</span>
                                                    </p>
                                                    <p>
                                                        <span>上传日期：</span>
                                                        <span>{addDate}</span>
                                                    </p>
                                                    <p>
                                                        <span>上传人：</span>
                                                        <span>{userName}</span>
                                                    </p>
                                                </div>
                                                <Btns source={file} btns={btns} />
                                            </List.Item>
                                        </div>
                                    );
                                })
                            ) : (
                                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                            )}
                        </div>
                    </BetterScroll>
                </div>
            </div>
        </Popup>
    );
}

FileList.propTypes = {
    infoKid: PropTypes.string,
    url: PropTypes.string,
    moduleId: PropTypes.number,
    typeId: PropTypes.number,
    detailPage: PropTypes.oneOf(["add", "edit", "sign", "view"]),
    wbsId: PropTypes.number,
    user: PropTypes.object,
    tableId: PropTypes.number,
};

FileInfo.propTypes = {
    visible: PropTypes.bool,
    visibleCb: PropTypes.func,
    recordId: PropTypes.string,
    joinId: PropTypes.string,
    setKid: PropTypes.string,
    page: PropTypes.oneOf(["add", "edit", "sign", "view"]),
    infoKid: PropTypes.string,
    moduleId: PropTypes.number,
    typeId: PropTypes.number,
    dataSrcId: PropTypes.string,
    wbsId: PropTypes.number,
    isAllFormat: PropTypes.string,
    isAdd: PropTypes.bool,
    user: PropTypes.object,
    tableId: PropTypes.number,
};

export default FileList;
